package com.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;

import com.model.MessageEnvelope;
import com.model.PacketHeader;
import com.model.ProtocolConstants;

public class Codec {
	public byte[] encodeMessageEnvelope(MessageEnvelope me, int msgType) throws IOException {
		ByteArrayOutputStream buf = new ByteArrayOutputStream();
		DataOutputStream convert = new DataOutputStream(buf);
		switch (msgType) {
		case ProtocolConstants.MSG_LOGIN_REQ:
			byte[] id = Arrays.copyOf(me.getId(), ProtocolConstants.MSG_LOGIN_ID_SIZE);
			convert.write(id);
			byte[] pwd = Arrays.copyOf(me.getPassword(), ProtocolConstants.MSG_LOGIN_PWD_SIZE);
			convert.write(pwd);
			break;
		}
		return buf.toByteArray();
	}

	public byte[] encodePacketHeader(PacketHeader header) {
		ByteArrayOutputStream buf = new ByteArrayOutputStream();
		DataOutputStream convert = new DataOutputStream(buf);

		try {
			convert.writeInt(header.getProtocol());
			convert.writeInt(header.getMsgType());
			convert.writeInt(header.getDataLength());
			convert.writeInt(header.getReserved());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return buf.toByteArray();

	}

	public PacketHeader decodePacketHeader(byte[] data) {
		ByteArrayInputStream buf = new ByteArrayInputStream(data);
		DataInputStream convert = new DataInputStream(buf);
		PacketHeader decodeHeader = new PacketHeader();
		try {
			decodeHeader.setProtocol(convert.readInt());
			decodeHeader.setMsgType(convert.readInt());
			decodeHeader.setDataLength(convert.readInt());
			decodeHeader.setReserved(convert.readInt());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return decodeHeader;
	}
	
	public MessageEnvelope decode_MSG_LOGIN_ACK(byte[] data) {
		ByteArrayInputStream buf = new ByteArrayInputStream(data);
		DataInputStream convert = new DataInputStream(buf);
		MessageEnvelope decodedData = new MessageEnvelope();
		try {
			byte[] serverMessage = new byte[ProtocolConstants.MSG_LOGIN_ACK_SIZE];
			convert.read(serverMessage, 0, ProtocolConstants.MSG_LOGIN_ACK_SIZE);
			decodedData.setServerMessage(new String(serverMessage, Charset.forName("US-ASCII")).getBytes());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return decodedData;
	}
}
